import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;

public class Snake {

	Node head=null;
	Node tail=null;
	int size=0;
	
	private Node node=new Node(20,30,Dir.L);
	private Yard y;
	
	public Snake(Yard y) {
		head=node;
		tail=node;
		size=1;
		this.y=y;
	}
	
	private void move() {
		addToHead();
		deletFromTail();
	}
	
	public void addToHead() {
		Node n=null;
		switch(head.dir) {
		case L:
			n=new Node(head.row,head.col-1,head.dir);
			break;
		case R:
			n=new Node(head.row,head.col+1,head.dir);
			break;
		case U:
			n=new Node(head.row-1,head.col,head.dir);
			break;
		case D:
			n=new Node(head.row+1,head.col,head.dir);
			break;
		}
		head.prior=n;
		n.next=head;
		head=n;
		size++;
	}
	
	private void deletFromTail() {
		if(tail==null) return;
		else{
		tail=tail.prior;
		tail.next=null;
		}
	}
	
	private Rectangle getRect() {
		return new Rectangle(Yard.BLOCK_SIZE*head.col, Yard.BLOCK_SIZE*head.row,head.w,head.h);
	}
	
	public void eat(Egg e) {
		if(this.getRect().intersects(e.getRect())) {
			e.reAppear();
			this.addToHead();
			y.score+=5;
		}
	}
	
	public void checkDead() {
		if(head.row<3||head.row>Yard.ROWS-1||head.col<0||head.col>Yard.COLS) {
			y.stop();
		}
		for(Node n=head.next;n!=null;n=n.next) {
			if(head.row==n.row&&head.col==n.col){
				y.stop();
			}
		}
	}

	public void draw(Graphics g) {
		if(size<=0) {
			return;
		}
		else {
			for(Node n=head;n!=null;n=n.next) {
				n.draw(g);
			}
		}
		move();
	} 
	
	private class Node {
		int w=Yard.BLOCK_SIZE;
		int h=Yard.BLOCK_SIZE;
		int row,col;
		Node next=null;
		Node prior=null;
		Dir dir=Dir.L;
		
		public Node(int row,int col,Dir dir) {
			this.row=row;
			this.col=col;
			this.dir=dir;		
		}
		public void draw(Graphics g) {
			Color c=g.getColor();
			g.setColor(Color.BLACK);
			g.fillRect(Yard.BLOCK_SIZE*col, Yard.BLOCK_SIZE*row,w,h);
			g.setColor(c);
		}
	}

	public void keyPressed(KeyEvent e) {
		int key=e.getKeyCode();
		switch(key) {
		case KeyEvent.VK_UP:
			if(head.dir!=Dir.D) {
				head.dir=Dir.U;
			}
			break;
		case KeyEvent.VK_DOWN:
			if(head.dir!=Dir.U) {
				head.dir=Dir.D;
			}
			break;
		case KeyEvent.VK_RIGHT:
			if(head.dir!=Dir.L) {
				head.dir=Dir.R;
			}
			break;
		case KeyEvent.VK_LEFT:
			if(head.dir!=Dir.R) {
				head.dir=Dir.L;
			}
			break;
		}
	}
	
}
